package com.qezhhnjy.cloud.zuul.filter;

import cn.hutool.http.HttpStatus;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author zhaoyangfu - 2020/7/30 15:43
 * zuul服务过滤
 */
@Component
@Slf4j
public class MyFilter extends ZuulFilter {

    /**
     * 返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型
     * pre:路由之前
     * routing:路由之时
     * post:路由之后
     * error:发送错误调用
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤的顺序
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 这里可以写逻辑判断,是否需要过滤,true表示需要过滤
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器的具体逻辑,可以很复杂,包括查sql,NoSql去判断该请求到底有没有权限访问.
     */
    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info("{}=>{}", request.getMethod(), request.getRequestURL().toString());
        String token = request.getParameter("token");
        if (token == null) {
            log.warn("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(HttpStatus.HTTP_UNAUTHORIZED);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
            return null;
        }
        return null;
    }
}
